package catchData;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class CatchFromXjypcg {
	
	private static final String CHECKCODE_URL = "http://passport.menet.com.cn/CheckCode.aspx";
	private static final String LOGIN_PAGE = "http://passport.menet.com.cn/login.aspx?BackURL=http%3a%2f%2fshuju.menet.com.cn%3a8080%2fDataQuery%2floginsso.jsp";
	private static final String MAIN_PAGE = "http://shuju.menet.com.cn:8080/DataQuery";
	private static final String SUB_PAGE = "/HappenIllPercent/";//子页面 
	private static final String SUB_ACTION = "getHappenIllPercentListAction.action";//子菜单action
	private static final String HOST = "shuju.menet.com.cn";
	private static final int PORT = 8080;
	private static final String LOGIN_USERNAME = "zjjf";
	private static final String LOGIN_PASSWORD = "id201318";
	private static final String PATH = "F:/CatchData";//存放文件夹
	private static int TOTALPAGE = 3;//页数
	private static String BDID = "6ea284f6ccab4682aa38d4f2ffa59e5a";//子页面对应id
	//cookies
	private static String COOKIES = 
			"JSESSIONID=52F3DC2D47DE9C977C2AD2F98205E646.tomcat1; menetuser=zjjf; JSESSIONID=04AF59F137897D2285317C0D9DE2E92B.tomcat1";
	
	private static HttpClient client;
	private JFrame jframe;
	private Icon icon;
	private JLabel jlabel;
	private JTextField checkCode;

	private void initHttpClient() {
		if (client == null) {
			MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
			client = new HttpClient(connectionManager);
			 client.getHostConfiguration().setHost(HOST, PORT, "http"); 
			// 配置服务器参量
			client.getParams().setCookiePolicy(
					CookiePolicy.BROWSER_COMPATIBILITY); // 配置Cookie策略为浏览器默认策略
			client.getParams().setParameter(
					"http.protocol.single-cookie-header", true);
			// client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
			// "UTF-8");
			client.getParams().setParameter(
					HttpMethodParams.HTTP_CONTENT_CHARSET, "gb2312");
			client.getHttpConnectionManager().getParams().setConnectionTimeout(
					300000);
			client.getHttpConnectionManager().getParams().setSoTimeout(300000);
		}
	}

	private void setHeaders(HttpMethod method) {
		method.getParams().setParameter("http.protocol.cookie-policy",
				CookiePolicy.BROWSER_COMPATIBILITY);
		method.setRequestHeader(
						"accept",
						"image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
		method.setRequestHeader("referer", MAIN_PAGE);
		method.setRequestHeader("accept-encoding",
				"UTF-8,GBK,GB2312,gzip,deflate");
		method.setRequestHeader("accept-language", "zh-CN");
		method.setRequestHeader("content-type",
				"application/x-www-form-urlencoded");
		method.setRequestHeader(
						"user-agent",
						"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; staticlogin:product=cboxf2010&act=login&info=ZmlsZW5hbWU9UG93ZXJXb3JkMjAxME94Zl9VbHRpbWF0ZS5leGUmbWFjPUY4RDgxQUY2MTgwQjQ3REQ5MUI5QkM4NjU3MzAwRkU3JnBhc3Nwb3J0PSZ2ZXJzaW9uPTIwMTAuNi4zLjYuMiZjcmFzaHR5cGU9MQ==&verify=b226e2d473bb8dbbb37568db14fee0e4; staticlogin:product=cboxf2010&act=login&info=ZmlsZW5hbWU9UG93ZXJXb3JkMjAxME94Zl9TcGVjaWFsLmV4ZSZtYWM9RjhEODFBRjYxODBCNDdERDkxQjlCQzg2NTczMDBGRTcmcGFzc3BvcnQ9JnZlcnNpb249MjAxMC42LjMuNS4yJmNyYXNodHlwZT0x&verify=94c65611a34cfb4964638346b072d76e; staticlogin:product=cboxf09&act=login&info=ZmlsZW5hbWU9UG93ZXJ3b3JkMjAwOU94Zi4yNTI2OS40MDExLmV4ZSZtYWM9RjhEODFBRjYxODBCNDdERDkxQjlCQzg2NTczMDBGRTcmcGFzc3BvcnQ9JnZlcnNpb249MjAwOS4wNS4yNS4zLjI3MiZjcmFzaHR5cGU9MQ==&verify=32e210faa8ce04f90dfc4225f98e80ac; aff-kingsoft-ciba; TheWorld)");
		method.setRequestHeader("host", HOST);
		method.setRequestHeader("connection", "Keep-Alive");
		method.setRequestHeader("cache-control", "no-cache");
		method.setRequestHeader("Cookie", COOKIES);//
	}

	private void saveDataFile(String sFolder, String data, long lid) {
		saveDataFile(sFolder, data, lid + "");
	}

	private void saveDataFile(String sFolder, String data, String sid) {
		PrintWriter out = null;
		String saveFile = sFolder + "/" + sid + ".htm";
		try {
//			out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(
//					saveFile), "utf-8"));
			out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(
					saveFile), "gb2312"));
			out.println(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
					out = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		System.out.println(saveFile);
		}
	}

	private void initJFrame() {
		if (jframe == null) {
			jframe = new JFrame();
			jframe.setTitle("输入校验码");
			jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			jframe.setLocationRelativeTo(null);
			Container container = jframe.getContentPane();
			container.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
			jlabel = new JLabel();
			refreshCheckCode();
			container.add(jlabel);
			jlabel.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent e) {
					refreshCheckCode();
				}
			});
			checkCode = new JTextField();
			checkCode.setPreferredSize(new Dimension(80, 25));
			container.add(checkCode);
			checkCode.addKeyListener(new KeyAdapter() {
				public void keyPressed(KeyEvent e) {
					if (e.getKeyCode() == KeyEvent.VK_ENTER) {
						doLogin(checkCode.getText());
					}
				}
			});
			JButton jbutton = new JButton();
			jbutton.setText("确 定");
			jbutton.setPreferredSize(new Dimension(80, 25));
			container.add(jbutton);
			jbutton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					doLogin(checkCode.getText());
				}
			});
			jframe.pack();
			jframe.setVisible(true);
			jframe.setAlwaysOnTop(true);
			jframe.setResizable(false);
		}
	}

	private void doLogin(String checkCodeText) {
//		System.out.println(checkCodeText);
		PostMethod method = null;
		PostMethod pm = null;
		String str = null;
		if (jframe != null) {
			jframe.removeAll();
			jframe.dispose();
			jframe = null;
		}
		try {
			PostMethod post = new PostMethod(LOGIN_PAGE);
			this.setHeaders(post);
			NameValuePair username = new NameValuePair("txtUsr",
					LOGIN_USERNAME);
			NameValuePair password = new NameValuePair("txtPwd",
					LOGIN_PASSWORD);
			NameValuePair checkCode = new NameValuePair("txtCheck",
					checkCodeText);
			NameValuePair submitx = new NameValuePair("imageField.x", "16");
			NameValuePair submity = new NameValuePair("imageField.y", "16");
			post.setRequestBody(new NameValuePair[] { username, password,
					checkCode ,submitx,submity});
			int statusCode = client.executeMethod(post);
//			System.out.println(statusCode);
			method = new PostMethod(MAIN_PAGE + SUB_PAGE + "index.jsp");
			this.setHeaders(method);
			client.executeMethod(method);
				for(int j=1; j<=TOTALPAGE;j++) {
					pm = new PostMethod(MAIN_PAGE + SUB_PAGE + SUB_ACTION);
					this.setHeaders(pm);
					NameValuePair diTitle=new NameValuePair("diTitle","");
					NameValuePair bdId = new NameValuePair("bdId", BDID);
					NameValuePair pageNow = new NameValuePair("pageNow", j+ "");
					pm.setRequestBody(new NameValuePair[]{diTitle,bdId,pageNow});
					int code = client.executeMethod(pm);
//					System.out.println(code);
					str = pm.getResponseBodyAsString();
//					System.out.println(str);
					this.saveDataFile(PATH, str, j);
					pm.releaseConnection();
				 }
			post.releaseConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void refreshCheckCode() {
		try {
			this.initHttpClient();
			GetMethod get = new GetMethod(CHECKCODE_URL);
			setHeaders(get);
			client.executeMethod(get);
			BufferedImage bi = ImageIO.read(get.getResponseBodyAsStream());
			icon = new ImageIcon(bi);
			jlabel.setIcon(icon);
			jlabel.repaint();
			get.releaseConnection();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		CatchFromXjypcg instance = new CatchFromXjypcg();
		instance.initJFrame();
	}
}